using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Admin.NET.Application.Service;

/// <summary>
/// 品牌型号管理
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class BrandService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<BrandModel> _modelRep;

	private readonly UserManager _userManager;

	public BrandService(SqlSugarRepository<BrandModel> modelRep, UserManager userManager)
	{
		_modelRep = modelRep;
		_userManager = userManager;
	}

	/// <summary>
	/// 获取品牌型号
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/brand/model/page")]
	public async Task<dynamic> ModelPage([FromQuery] BrandModelInput input)
	{
		ISugarQueryable<BrandModel> query = _modelRep.Context.Queryable<BrandModel>().WhereIF(!string.IsNullOrWhiteSpace(input.Name), (BrandModel u) => u.Name.Contains(input.Name)).WhereIF(input.Type.HasValue, (BrandModel u) => u.Type == input.Type);
		query = query.OrderBuilder(input);
		return await query.ToPagedListAsync(input.Page, input.PageSize);
	}

	/// <summary>
	/// 新增型号
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/brand/model/add")]
	public async Task AddModel(AddBrandModelInput input)
	{
		if (await _modelRep.IsAnyAsync((BrandModel a) => a.Name == input.Name))
		{
			throw Oops.Bah("当前型号已存在");
		}
		BrandModel entity = input.Adapt<BrandModel>();
		await _modelRep.InsertAsync(entity);
	}

	[HttpPost("/brand/model/edit")]
	public async Task EditModel(EditBrandModelInput input)
	{
		if (await _modelRep.IsAnyAsync((BrandModel a) => a.Id != input.Id && a.Name == input.Name))
		{
			throw Oops.Bah("当前型号名称已存在");
		}
		BrandModel entity = input.Adapt<BrandModel>();
		await _modelRep.UpdateAsync(entity);
	}

	/// <summary>
	/// 删除型号
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/brand/model/delete")]
	public async Task DeleteModel(DeleteBrandModelInput input)
	{
		BrandModel entity = input.Adapt<BrandModel>();
		await _modelRep.DeleteAsync(entity);
	}

	/// <summary>
	/// 根据类别获取拥有的品牌型号
	/// </summary>
	/// <param name="type"></param>
	/// <returns></returns>
	[HttpGet("/brand/getbrandmodels")]
	public async Task<dynamic> GetBrandModels([FromQuery] int type)
	{
		return await (from l in _modelRep.Context.Queryable<BrandModel>()
			where l.Type == (int?)type
			select new
			{
				label = l.Name,
				value = l.Id
			}).ToListAsync();
	}
}
